﻿using SqlSugar;
using System;
using System.Configuration;
using System.IO;
using System.Windows;
using Zo.ExcelBox.Base;
using Zo.ExcelBox.Models;
using System.Configuration;
using System.Runtime.InteropServices;
using Newtonsoft.Json;


namespace Zo.ExcelBox
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            InitializeData();
        }

        static string Env = "";

        void InitializeData()
        {

            var env = ConfigurationManager.AppSettings["Env"];

            var rootPath = AppDomain.CurrentDomain.BaseDirectory;
            var dbPath = Path.Combine(rootPath, "db");


            if (env == "dev")
            {
                var drive = Path.GetPathRoot(rootPath);
                dbPath = Path.Combine(drive, "Zo-ExcelBox-Temp");
            }

            if (!Directory.Exists(dbPath))
            {
                Directory.CreateDirectory(dbPath);
            }


            //建立配置文件
            var appJsonFile = Path.Combine(dbPath, "app.json");
            if (!System.IO.File.Exists(appJsonFile))
            {
                var itext = JsonConvert.SerializeObject(new AppContextJsonConfig());
                System.IO.File.WriteAllText(appJsonFile, itext, System.Text.Encoding.UTF8);
            }
            else
            {
                var jsonText = System.IO.File.ReadAllText(appJsonFile, System.Text.Encoding.UTF8);
                AppContext.JsonConfig= JsonConvert.DeserializeObject<AppContextJsonConfig>(jsonText);
            }


            var dbFileName = "zo_excelbox.db";
            var connectionString = $"DataSource={Path.Combine(dbPath, dbFileName)}";

            DbContext.ConnectionString = connectionString;
            var db = new SqlSugarClient(new ConnectionConfig()
            {
                DbType = SqlSugar.DbType.Sqlite,
                ConnectionString = connectionString,
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true,
            });

            db.CodeFirst.InitTables(typeof(JudicialCase));
            db.CodeFirst.InitTables(typeof(JudicialCaseTransactionRecord));

        }
    }

    public enum Envionment
    {
        Dev = 0,
        Pro = 1
    }
}
